package com.lbyl.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @author libin996@outlook.com
 */

public class LocalCacheUtil {
    private static final String TAG = "LocalCacheUtil";
    private static final String LOCAL_CACHE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/ptns_cache";

    /**
     * 写本地缓存
     *
     * @param urlStr
     * @param bitmap
     */
    public void setLocalCache(String urlStr, Bitmap bitmap) {
        if (bitmap == null || urlStr == null) {
            Log.e(TAG, "setLocalCache: bitmap或urlstr为空");
            return;
        }
        File dir = new File(LOCAL_CACHE_PATH );
        if (!dir.exists() || !dir.isDirectory()) {
            dir.mkdirs();//创建缓存文件夹
        }

        try {//md5保证文件名格式正确
            String fileName =MD5Encoder.encode(urlStr);
            File cacheFile;
            cacheFile = new File(dir+fileName);

            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(cacheFile));

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    //读本地缓存

    /**
     * 取本地缓存
     *
     * @param urlStr
     * @return bitmap或null
     */
    public  Bitmap getLocalCache(String urlStr) {
        Bitmap bitmap = null;
        try {
            File cacheFile = new File(LOCAL_CACHE_PATH, MD5Encoder.encode(urlStr));
            if (cacheFile.exists()) {
                bitmap = BitmapFactory.decodeStream(new FileInputStream(cacheFile));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i(TAG, "getLocalCache: 从本地加载");
        return bitmap;
    }

}
